# -*- coding:utf-8 -*-
from flask import json
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_login import login_required, login_user, logout_user

from app.actions.auth import auth
from app.database.models import User

__author__ = 'JiangW'


@auth.route('/login', methods=['GET', 'POST'])
def auth_login():
    if request.method == 'GET':
        return render_template('auth/login_view.html')
    else:
        res = {'code': 1000}
        account = request.values.get('account')
        password = request.values.get('password')
        next_url = request.args.get('next')
        if account and password:
            current_user = User.query.filter_by(account=account).first()
            if current_user and current_user.verify_password(password):
                login_user(current_user, True)
                res['next'] = next_url
            else:
                res['code'] = 1001
        else:
            res['code'] = 1001

        return json.dumps(res)


@auth.route('/logout', methods=['GET', 'POST'])
@login_required
def auth_logout():
    logout_user()
    return redirect(url_for('auth.auth_login'))